package com.gcloud.image.driver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.gcloud.common.util.SystemUtil;
import com.gcloud.core.exception.GCloudException;

/**
 * 镜像的后端存储为file，镜像分发到rbd
 *
 */
@Component
public class FileStoreRbdDriver implements IImageStoreNodeDriver{

	@Override
	public void downloadImage(String sourceFilePath, String imageId, String target) {
		//将qcow2镜像文件转化为raw格式的临时文件
		//qemu-img convert -f qcow2 -O raw windows2003.qcow2 windows2003.raw
		String[] formatCmd = new String[]{"qemu-img", "convert", "-f", "qcow2", "-O", "raw", sourceFilePath, sourceFilePath + ".raw"};
        this.exec(formatCmd, "::qcow2镜像文件转化为raw格式失败");
		//将raw文件copy到rbd上
		//rbd -p images import windows2003.raw --image ${imageId}
        String[] copyCmd = new String[]{"rbd", "-p", "images", "import", sourceFilePath + ".raw", "--image", imageId};
        this.exec(copyCmd, "::将raw格式镜像文件copy到images池上失败");
        //删除临时文件
        String[] deleteCmd = new String[]{"rm", "-f", sourceFilePath + ".raw"};
        this.exec(deleteCmd, "::删除临时raw格式镜像文件失败");
        
	}
	
	private void exec(String[] cmd, String errorCode) {
		int res = SystemUtil.runAndGetCode(cmd);
		if(res != 0) {
			throw new GCloudException(errorCode);
		}
	}
}
